<?php

namespace backend\controllers;

use Yii;
use backend\models\AdminInfo;
use backend\models\AdminInfoSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

use yii\filters\AccessControl;
use yii\web\ForbiddenHttpException;
use common\models\UserInfo;
use backend\models\SysUserDesigner;

/**
 * AdminInfoController implements the CRUD actions for AdminInfo model.
 */
class AdminInfoController extends Controller
{
    public function behaviors()
    {
    	
        return [
         /*   'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['create', 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],*/
        
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    public function beforeAction($action)
    {
    	//如果未登录，则直接跳转
    	if(Yii::$app->user->isGuest){
    		return $this->redirect(['/site/login']);
    	}
    	
    	
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	if(\Yii::$app->user->can($controller.'/'.$action)){
    		return true;
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    	} 
    }
    /**
     * Lists all AdminInfo models.
     * @return mixed
     */
    public function actionIndex()
    {
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;

    //	if(Yii::$app->user->can($action.'-'.$controller))
    	//{
	        $searchModel = new AdminInfoSearch();
	        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
	        $all = AdminInfo::find()->all();
		
	        return $this->render('index', [
	            'searchModel' => $searchModel,
	            'dataProvider' => $dataProvider,
	        		'all'=>$all,
	        ]);
    	//}
    	//else {
    	//	throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    	//}
    }

    /**
     * Displays a single AdminInfo model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
    	$model = $this->findModel($id);
    	$model->confirmed_at = !empty($model->confirmed_at)?date('Y-m-d H:i:s',$model->confirmed_at):$model->confirmed_at;
    	$model->created_at = !empty($model->created_at)?date('Y-m-d H:i:s',$model->created_at):$model->created_at;
    	$model->lastlogin_at = !empty($model->lastlogin_at)?date('Y-m-d H:i:s',$model->lastlogin_at):$model->lastlogin_at;
    	$model->updated_at = !empty($model->updated_at)?date('Y-m-d H:i:s',$model->updated_at):$model->updated_at;
    	$model->blocked_at = !empty($model->blocked_at)?date('Y-m-d H:i:s',$model->blocked_at):$model->blocked_at;
    	 	
		$status_array =array('1'=>'active','2'=>'delete','3'=>'block');
		$model->status = isset($status_array[$model->status])?$status_array[$model->status]:$model->status;
		
        return $this->render('view', [
            'model' => $model,
        ]);
    }

    /**
     * Creates a new AdminInfo model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
    	
        $model = new AdminInfo();
        $user_model= UserInfo::get_type_user("5");//运营商
        if ($model->load(Yii::$app->request->post())&&$model->validate()) {
        	
        	$model->user_id = (int)$model->user_id;
        	/*if(!$model->user_id) $model->user_type = '1';
        	else $model->user_type ='5';
        	$admin_user = AdminInfo::unique_admin_user(0, (int)$model->user_id);
        	 
        	$admin_username = $admin_user['username'];
        	if(!is_bool($admin_user)){
        		echo '<script type="text/javascript">';
        		echo 'alert("运营商账号已存在：'.$admin_username.'");';
        		echo 'history.back(-1);';
        		echo '</script>';
        		return ;
        	}
        	*/
        	$designer = SysUserDesigner::findOne($model->user_id);
        	$model->user_address = $designer ? $designer->address : '';
        	
        	$model->createadmin();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            	'user_model'=>$user_model,
            ]);
        }
    }

    /**
     * Updates an existing AdminInfo model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        if($id == 1 && Yii::$app->user->identity->id !=1)
        { //admin的账号由admin修改
        	Yii::$app->session->setFlash('danger',Yii::t('app','Sorry , You don\'t have permission'));
        	return $this->redirect((['admin-info/index']));
        }
    	$model = $this->findModel($id);
    	$user_model= UserInfo::get_type_user("5");//运营商
        if ($model->load(Yii::$app->request->post())) {
        	//验证管理员已存在
        	$model->user_id = (int)$model->user_id;
        	/*if(!$model->user_id) $model->user_type = '1';
        	else $model->user_type ='5';*/
        	
        	/*$admin_user = AdminInfo::unique_admin_user($model->id, $model->user_id);	
        	$admin_username = $admin_user['username'];
        	if(!is_bool($admin_user)){
        		echo '<script type="text/javascript">';
        		echo 'alert("运营商账号已存在：'.$admin_username.'");';
        		echo 'history.back(-1);';
        		echo '</script>';
        		return ;
        	}
        	*/
        	$designer = SysUserDesigner::findOne($model->user_id);
        	$model->user_address = $designer ? $designer->address : '';
        	
        	if($model->password != null)
        	{
        		$model->password_hash = $model->update_password($model->password);
        	}
        	
        	$model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            	'user_model'=>$user_model,
            ]);
        }
    }

    /**
     * Deletes an existing AdminInfo model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the AdminInfo model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return AdminInfo the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = AdminInfo::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
